'''
Created on 26 nov. 2010

@author: christianp
'''
import threading, time
from wx import wx
from XML.XMLSeedOutput import XMLSeedOutput
from copy import copy

class PropertyEvents(object):
    
    __pHandler = None
    __lock = None
    
    def __init__(self, pHandler):
        self.__lock = threading.Lock()
        self.__pHandler = pHandler
        
    def CancelSeedRun(self, event):
        seed = self.__pHandler.layerHandler.GetTileSeed(self.__pHandler.lboxTileSeeds.Items[self.__pHandler.lboxTileSeeds.GetSelection()])
        self.__pHandler.layerHandler.QuitTileSeed(seed)
        self.__pHandler.layerHandler.ResetSeed(seed)
    
    def StartSeedRun(self, event):
       
        seed = self.__pHandler.layerHandler.GetTileSeed(self.__pHandler.lboxTileSeeds.Items[self.__pHandler.lboxTileSeeds.GetSelection()])
        self.__pHandler.layerHandler.tile_seeder.SetLabels(self.__pHandler.gaugeTiles, self.__pHandler.stxtGaugeDone, self.__pHandler.stxtGaugeRemaining, self.__pHandler.labelTilesToBeDone, self.__pHandler.labelTilesFailed)
        
        self.__pHandler.layerHandler.ProccessTileSeed(seed)
        
        if not(self.__pHandler.layerHandler.inProcess):
            self.__pHandler.layerHandler.StartProcessing()
        
        seedInProcess = self.__pHandler.lboxTileSeeds.GetClientData(self.__pHandler.lboxTileSeeds.GetSelection())
        if not seedInProcess:                
            seedInProcess = True

    def ProcessAllSeeds(self, event):
        for thread in threading.enumerate():
            print(thread.getName())
    
    def SetSeedInfo(self, seed):
        seed.SetSeedExtent(seed.tile_schema.extent)
        seed.SetSeedZoomLvl(seed.tile_schema.resolutions)
        seedZoomLvl = seed.GetSeedZoomLvl()
        
        for i in range(0, len(seedZoomLvl)):
            item = seedZoomLvl[i]
            self.lboxZoomLevelsSeed.Insert(str(copy(item[0])), i, copy(item))
        self.updateSeeExtent(seed.GetSeedExtent())
        
    def SetLayerInfo(self, seed):
        for i in range(0, len(seed.tile_schema.resolutions)):
            self.__pHandler.lboxZoomLevelsLayer.Insert(str(i), i, seed.tile_schema.resolutions[i])

        self.__pHandler.lLayerMinX.SetLabel(str(seed.tile_schema.extent.getMinX()))
        self.__pHandler.lLayerMinY.SetLabel(str(seed.tile_schema.extent.getMinY()))
        self.__pHandler.lLayerMaxX.SetLabel(str(seed.tile_schema.extent.getMaxX()))
        self.__pHandler.lLayerMaxY.SetLabel(str(seed.tile_schema.extent.getMaxY()))
        
        self.__pHandler.SetLayerExtent(seed.tile_schema.extent)
        self.__pHandler.SetSeedInfo(seed)

    def TileSeedSelected(self, event):
        name = self.__pHandler.lboxTileSeeds.Items[self.__pHandler.lboxTileSeeds.GetSelection()]
        seed = self.__pHandler.layerHandler.GetTileSeed(name)
        
        self.__pHandler.ClearLayerLabels()
        self.__pHandler.ClearSeedLabels()
        
        if self.__pHandler.layerHandler.GetTileSeed(name).HasLayerInfo():
            self.SetLayerInfo(seed)
        else:
            self.__pHandler.layerHandler.GetTileSeedInfo(seed.href, seed, self.__pHandler.SetLayerInfo)
                
        if (self.__pHandler.layerHandler.inProcess):
            self.__pHandler.layerHandler.ShowTileSeed(seed.tile_schema.name)
                
    def AddZoomLvl(self, event):
        layer = self.__pHandler.layerHandler.GetTileSeed(self.__pHandler.lboxTileSeeds.Items[self.__pHandler.lboxTileSeeds.GetSelection()])
        if not self.__pHandler.layerHandler.IsTileSeedActive(layer.tile_schema.name):
            if self.__pHandler.IsItemSelectedInList(self.__pHandler.lboxZoomLevelsLayer):
                value = copy(event.ClientData)
                found = False
                for item in self.__pHandler.lboxZoomLevelsSeed.Items:
                    if (str(item) == str(value[0])):
                        found = True
                if not found:
                    layer = self.__pHandler.layerHandler.GetTileSeed(self.__pHandler.lboxTileSeeds.Items[self.__pHandler.lboxTileSeeds.GetSelection()])
                    seedInProcess = self.__pHandler.lboxTileSeeds.GetClientData(self.__pHandler.lboxTileSeeds.GetSelection())
                    if not seedInProcess:
                        self.__pHandler.AddSeedZoomLvl(value)
                        layer.AddSeedZoomLvl(value)
    
    def RemoveZoomLvl(self, event):
        layer = self.__pHandler.layerHandler.GetTileSeed(self.__pHandler.lboxTileSeeds.Items[self.__pHandler.lboxTileSeeds.GetSelection()])
        if not self.__pHandler.layerHandler.IsTileSeedActive(layer.tile_schema.name):
            if self.__pHandler.IsItemSelectedInList(self.__pHandler.lboxZoomLevelsSeed):
                value = event.ClientData
                layer = self.__pHandler.layerHandler.GetTileSeed(self.__pHandler.lboxTileSeeds.Items[self.__pHandler.lboxTileSeeds.GetSelection()])
                
                self.__pHandler.lboxZoomLevelsSeed.Delete(self.__pHandler.lboxZoomLevelsSeed.GetSelection())
                layer.RemoveSeedZoomLvl(value[0])
    
    def AddSeedToList(self, event):
        self.__lock.acquire()
        try:
            try:
                seed = copy(event.ClientData)
            except:
                seed = copy(event)
            
            if not self.__pHandler.layerHandler.ContainsTileSeed(seed.tile_schema.name):
                self.__pHandler.lboxTileSeeds.Insert(seed.tile_schema.name, len(self.__pHandler.lboxTileSeeds.Items), seed)
                self.__pHandler.layerHandler.AddTileSeed(copy(seed))
            
            if len(self.__pHandler.lboxTileSeeds.Items) == 1:
                self.__pHandler.lboxTileSeeds.Select(0)
                self.TileSeedSelected(self.__pHandler.lboxTileSeeds.Items[0])
            
        finally:
            self.__lock.release()
    
    def IsTileSeedActive(self, seed):
        '''try:
            seed = event.ClientData
        except:
            seed = event
        '''
        return self.__pHandler.layerHandler.IsTileSeedActive(seed.tile_schema.name)
     
    def RemoveSeedFromList(self, seed):
        self.__lock.acquire()
        try:
            '''
            try:
                seed = event.ClientData
            except:
                seed = event
            '''
            #layer = self.__pHandler.layerHandler.GetTileSeed(self.__pHandler.lboxTileSeeds.Items[self.__pHandler.lboxTileSeeds.GetSelection()])
            if not(seed is None):
                if not(seed.active):
                    self.Remove(seed)
                    self.__pHandler.layerHandler.RemoveTileSeed(seed.tile_schema.name)
                    self.__pHandler.ClearLayerLabels()
                    self.__pHandler.ClearSeedLabels()
                    if (len(self.__pHandler.lboxTileSeeds.Items) > 0):
                        self.__pHandler.lboxTileSeeds.Select(0)
                        self.TileSeedSelected(None)
                    return True
            
            return False            
            '''
            if not seed.active:
                if self.__pHandler.layerHandler.ContainsTileSeed(seed.tile_schema.name): 
                    seedIndex = self.__pHandler.layerHandler.GetTileSeedIndex(seed.tile_schema.name)
                    if not seedIndex is None:
                        if self.__pHandler.lboxTileSeeds.IsSelected(seedIndex):
                            self.__pHandler.ClearLayer()
                            self.__pHandler.ClearSeed()
                        self.__pHandler.lboxTileSeeds.Delete(seedIndex)
                        self.__pHandler.layerHandler.RemoveTileSeed(seed.tile_schema.name)
                    if len(self.__pHandler.lboxTileSeeds.Items) > 0:
                        self.__pHandler.lboxTileSeeds.Select(0)
                        self.TileSeedSelected(None)'''
        finally:
            self.__lock.release()
    
    def FileDialog(self, message, function):
        filters = 'Seed files (*.seed)|*.seed|All files (*.*)|*.*'

        dialog = wx.FileDialog ( None, message = message, wildcard = filters, style = function )
        
        if dialog.ShowModal() == wx.ID_OK:
            directory = dialog.GetDirectory()
            fileName = dialog.GetFilename()
            return (directory, fileName)
        else:
            print 'Cancel'
        
        dialog.Destroy()
    
    def FileSaveHandler(self, fileLocation):
        items = []
        for i in range(0, len(self.__pHandler.lboxTileSeeds.Items)):
            #layer = self.__pHandler.layerHandler.GetTileSeed(self.__pHandler.lboxTileSeeds.Items[self.__pHandler.lboxTileSeeds.GetSelection()])
            layer = self.__pHandler.layerHandler.GetTileSeed(self.__pHandler.lboxTileSeeds.Items[i])
            items.append(layer)
        
        saveTileSeed = XMLSeedOutput()
        saveTileSeed.save(items, fileLocation)
    
    def RemoveTileSeedFromList(self, event=None):
        
        layer = self.__pHandler.layerHandler.GetTileSeed(self.__pHandler.lboxTileSeeds.Items[self.__pHandler.lboxTileSeeds.GetSelection()])
        bUpdate = self.RemoveSeedFromList(layer)
        if bUpdate:
            self.__pHandler.UpdateMainWindowList(layer.tile_schema.name)
        '''if not(layer.active):
            self.Remove(layer)
            
            if not(layer is None):
                self.__pHandler.layerHandler.RemoveTileSeed(layer.tile_schema.name)
            
            if (len(self.__pHandler.lboxTileSeeds.Items) > 0):
                self.__pHandler.lboxTileSeeds.Select(0)
                '''
    
    def Remove(self, layer):
        for i in range(0, len(self.__pHandler.lboxTileSeeds.Items)):
            name = self.__pHandler.lboxTileSeeds.Items[i]
            if name == layer.tile_schema.name:
                self.__pHandler.lboxTileSeeds.Delete(i)
                return
    
    def OnSave(self, event=None):
        fileLocation = self.FileDialog("Save seed", wx.SAVE)
        self.FileSaveHandler(fileLocation)
            
    def OnOpen(self, event=None):
        fileLocation = self.FileDialog("Open seed", wx.OPEN)
    
    def OnClose(self, event):
        sDown = self.__pHandler.layerHandler.AreTileSeedsActive()

        self.__pHandler.layerHandler.QuitAllTileSeeds()

        while sDown:
            print("PropertyEvents: OnClose inProgress")
            sDown = self.__pHandler.layerHandler.AreTileSeedsActive()
            time.sleep(0.1)

        self.__pHandler.UpdateMainWindow()
        self.__pHandler.pWindow.Destroy()
    
    def OnQuit(self, event):
        print("PropertyEvents: OnQuit")
        sDown = self.__pHandler.layerHandler.AreTileSeedsActive()
        
        self.__pHandler.layerHandler.QuitAllTileSeeds()

        while sDown:
            print("PropertyEvents: OnQuit inProgress")
            sDown = self.__pHandler.layerHandler.AreTileSeedsActive()
            time.sleep(0.1)

        self.__pHandler.UpdateMainWindow()
        self.__pHandler.pWindow.Destroy()
    
    def OnAbout(self, event):
        dlg = wx.MessageDialog(self, "This sample program shows off\n"
                              "frames, menus, statusbars, and this\n"
                              "message dialog.",
                              "About Me", wx.OK | wx.ICON_INFORMATION)
        dlg.ShowModal()
        dlg.Destroy()